<template>
  <div class="file-move-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-icon">
          <el-icon><FolderOpened /></el-icon>
        </div>
        <div class="header-text">
          <h2>文件移动管理</h2>
          <p>管理文件在不同文件夹间的移动</p>
        </div>
      </div>
    </div>

    <!-- 文件夹列表 -->
    <div class="folders-section">
      <el-card>
        <template #header>
          <div class="section-header">
            <h3>可用文件夹</h3>
            <el-button type="primary" size="small" @click="$router.push('/new')">
              <el-icon><Plus /></el-icon>
              新建文件夹
            </el-button>
          </div>
        </template>

        <div v-if="state.length === 0" class="empty-state">
          <el-empty description="暂无文件夹">
            <el-button type="primary" @click="$router.push('/new')">
              创建第一个文件夹
            </el-button>
          </el-empty>
        </div>

        <div v-else class="folder-grid">
          <div
            v-for="folder in state"
            :key="folder.id"
            class="folder-item"
            :class="{ active: selectedFolderId === folder.id }"
            @click="selectFolder(folder)"
          >
            <div class="folder-icon">
              <el-icon><Folder /></el-icon>
            </div>
            <div class="folder-info">
              <div class="folder-name">{{ folder.folder_name }}</div>
              <div class="folder-meta">
                <span class="folder-id">ID: {{ folder.id }}</span>
                <span class="folder-date">{{ formatDate(folder.created_at) }}</span>
              </div>
            </div>
            <div class="folder-badge" v-if="selectedFolderId === folder.id">
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 文件列表 -->
    <div class="files-section">
      <el-card>
        <template #header>
          <div class="section-header">
            <h3>文件列表</h3>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索文件..."
                clearable
                style="width: 200px; margin-right: 12px;"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button @click="refreshFiles">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <div v-if="filteredFiles.length === 0" class="empty-state">
          <el-empty description="暂无文件">
            <el-button type="primary" @click="$router.push('/fileupload')">
              上传文件
            </el-button>
          </el-empty>
        </div>

        <el-table
          v-else
          :data="filteredFiles"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column label="文件名" min-width="200">
            <template #default="{ row }">
              <div class="file-cell">
                <div class="file-icon">{{ getFileIcon(row.filename) }}</div>
                <span class="file-name">{{ row.filename }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="created_at" label="创建时间" width="180" />

          <el-table-column label="当前文件夹" width="150">
            <template #default="{ row }">
              <el-tag v-if="row.folder_name" type="info" size="small">
                {{ row.folder_name }}
              </el-tag>
              <el-tag v-else type="warning" size="small">
                根目录
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="moveFile(row)"
                :disabled="!selectedFolderId"
              >
                <el-icon><FolderOpened /></el-icon>
                移动
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteFile(row.id)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 批量操作 -->
        <div v-if="selectedFiles.length > 0" class="batch-actions">
          <div class="batch-info">
            已选择 {{ selectedFiles.length }} 个文件
          </div>
          <div class="batch-buttons">
            <el-button
              type="primary"
              @click="batchMoveFiles"
              :disabled="!selectedFolderId"
            >
              <el-icon><FolderOpened /></el-icon>
              批量移动到选中文件夹
            </el-button>
            <el-button type="danger" @click="batchDeleteFiles">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import {
  FolderOpened,
  Plus,
  Folder,
  Check,
  Search,
  Refresh,
  Delete
} from "@element-plus/icons-vue";
import { getFolderApi, fileListApi, moveApi, deleteApi } from "@/utils/api.js";

const router = useRouter();

// 响应式数据
const state = ref([]);
const filelist = ref([]);
const loading = ref(false);
const searchKeyword = ref("");
const selectedFolderId = ref(null);
const selectedFiles = ref([]);

const user_id = localStorage.getItem("id");

// 计算属性
const filteredFiles = computed(() => {
  if (!searchKeyword.value) return filelist.value;
  return filelist.value.filter(file =>
    file.filename.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    // 获取文件夹列表
    const folderResponse = await getFolderApi({ id: user_id });
    if (folderResponse.code === 200) {
      state.value = folderResponse.data.data.map((item) => ({
        ...item,
        created_at: item.created_at.split("T")[0],
      }));
    }

    // 获取文件列表
    const fileResponse = await fileListApi({ user_id });
    if (fileResponse) {
      fileResponse.forEach((item) => {
        item.created_at = item.created_at.replace("T", " ").split(".")[0];
        // 根据文件的文件夹 ID 找到对应的文件夹名称
        const folder = state.value.find((folder) => folder.id === item.folder_id);
        if (folder) {
          item.folder_name = folder.folder_name;
        }
      });
      filelist.value = fileResponse;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
};

const selectFolder = (folder) => {
  selectedFolderId.value = folder.id;
  ElMessage.info(`已选择文件夹: ${folder.folder_name}`);
};

const refreshFiles = () => {
  loadData();
  ElMessage.success("已刷新数据");
};

const handleSelectionChange = (selection) => {
  selectedFiles.value = selection;
};

// 移动单个文件
const moveFile = async (file) => {
  if (!selectedFolderId.value) {
    ElMessage.warning("请先选择目标文件夹");
    return;
  }

  try {
    const targetFolder = state.value.find(f => f.id === selectedFolderId.value);
    await ElMessageBox.confirm(
      `确定要将文件 "${file.filename}" 移动到文件夹 "${targetFolder.folder_name}" 吗？`,
      "确认移动",
      {
        confirmButtonText: "确定移动",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    const res = await moveApi({ id: file.id, folder_id: selectedFolderId.value });
    if (res.code === 200) {
      ElMessage.success("文件移动成功");
      await loadData();
    } else {
      ElMessage.error(res.message || "移动失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("移动文件失败:", error);
      ElMessage.error("移动失败，请重试");
    }
  }
};

// 批量移动文件
const batchMoveFiles = async () => {
  if (!selectedFolderId.value) {
    ElMessage.warning("请先选择目标文件夹");
    return;
  }

  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请先选择要移动的文件");
    return;
  }

  try {
    const targetFolder = state.value.find(f => f.id === selectedFolderId.value);
    await ElMessageBox.confirm(
      `确定要将 ${selectedFiles.value.length} 个文件移动到文件夹 "${targetFolder.folder_name}" 吗？`,
      "确认批量移动",
      {
        confirmButtonText: "确定移动",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    // 批量移动
    const promises = selectedFiles.value.map(file =>
      moveApi({ id: file.id, folder_id: selectedFolderId.value })
    );

    const results = await Promise.all(promises);
    const successCount = results.filter(res => res.code === 200).length;

    if (successCount === selectedFiles.value.length) {
      ElMessage.success(`成功移动 ${successCount} 个文件`);
    } else {
      ElMessage.warning(`移动完成，成功 ${successCount} 个，失败 ${selectedFiles.value.length - successCount} 个`);
    }

    await loadData();
    selectedFiles.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error("批量移动失败:", error);
      ElMessage.error("批量移动失败，请重试");
    }
  }
};

// 删除单个文件
const deleteFile = async (id) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这个文件吗？此操作不可恢复。",
      "确认删除",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const res = await deleteApi({ id });
    if (res.code === 200) {
      ElMessage.success("删除文件成功");
      await loadData();
    } else {
      ElMessage.error(res.message || "删除文件失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("删除文件失败:", error);
      ElMessage.error("删除失败，请重试");
    }
  }
};

// 批量删除文件
const batchDeleteFiles = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请先选择要删除的文件");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？此操作不可恢复。`,
      "确认批量删除",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 批量删除
    const promises = selectedFiles.value.map(file => deleteApi({ id: file.id }));
    const results = await Promise.all(promises);
    const successCount = results.filter(res => res.code === 200).length;

    if (successCount === selectedFiles.value.length) {
      ElMessage.success(`成功删除 ${successCount} 个文件`);
    } else {
      ElMessage.warning(`删除完成，成功 ${successCount} 个，失败 ${selectedFiles.value.length - successCount} 个`);
    }

    await loadData();
    selectedFiles.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败，请重试");
    }
  }
};

// 获取文件图标
const getFileIcon = (filename) => {
  if (!filename) return '📄';

  const ext = filename.split('.').pop()?.toLowerCase();

  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) return '🖼️';
  if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(ext)) return '🎬';
  if (['mp3', 'wav', 'flac', 'aac', 'ogg'].includes(ext)) return '🎵';
  if (['pdf'].includes(ext)) return '📕';
  if (['doc', 'docx'].includes(ext)) return '📘';
  if (['xls', 'xlsx'].includes(ext)) return '📗';
  if (['ppt', 'pptx'].includes(ext)) return '📙';
  if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return '📦';
  if (['txt', 'md', 'json', 'xml', 'csv'].includes(ext)) return '📝';
  if (['js', 'ts', 'html', 'css', 'vue', 'py', 'java', 'cpp'].includes(ext)) return '💻';

  return '📄';
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN');
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>
<style lang="less" scoped>
.file-move-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;

  .header-content {
    display: flex;
    align-items: center;
    gap: 16px;

    .header-icon {
      width: 50px;
      height: 50px;
      background: linear-gradient(135deg, #409eff, #67c23a);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 20px;
    }

    .header-text {
      h2 {
        margin: 0 0 4px 0;
        color: #303133;
        font-size: 20px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.folders-section,
.files-section {
  margin-bottom: 24px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      align-items: center;
    }
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }

  .folder-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
    margin-top: 16px;

    .folder-item {
      position: relative;
      display: flex;
      align-items: center;
      padding: 16px;
      border: 2px solid #ebeef5;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.3s;
      background: white;

      &:hover {
        border-color: #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
        transform: translateY(-2px);
      }

      &.active {
        border-color: #409eff;
        background: #f0f9ff;

        .folder-icon {
          background: #409eff;
          color: white;
        }
      }

      .folder-icon {
        width: 48px;
        height: 48px;
        background: linear-gradient(135deg, #ffd54f, #ffb74d);
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        color: white;
        font-size: 20px;
        transition: all 0.3s;
      }

      .folder-info {
        flex: 1;
        min-width: 0;

        .folder-name {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .folder-meta {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: #909399;

          .folder-id {
            font-family: monospace;
          }
        }
      }

      .folder-badge {
        width: 24px;
        height: 24px;
        background: #67c23a;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 14px;
      }
    }
  }
}

.file-cell {
  display: flex;
  align-items: center;
  gap: 8px;

  .file-icon {
    font-size: 16px;
  }

  .file-name {
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 8px;

  .batch-info {
    color: #606266;
    font-size: 14px;
  }

  .batch-buttons {
    display: flex;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .file-move-container {
    padding: 15px;
  }

  .folder-grid {
    grid-template-columns: 1fr;
  }

  .batch-actions {
    flex-direction: column;
    gap: 12px;
    text-align: center;

    .batch-buttons {
      width: 100%;
      justify-content: center;
    }
  }

  .section-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>
